import { Draw } from "../Draw/Draw";
import { wheel } from "./handle/global/wheel";

export class GlobalEvent {
  private draw: Draw;
  constructor(draw: Draw) {
    this.draw = draw;
    this.addEvent();
  }

  /** 解决 bind 移除异常问题 */
  private bindWheel = this.wheel.bind(this);
  private bindFullscreenchange = this.fullscreenchange.bind(this);

  // 监听全局事件
  private addEvent() {
    window.addEventListener("contextmenu", this.contextmenu);
    window.addEventListener("wheel", this.bindWheel, { passive: false });
    document.addEventListener("fullscreenchange", this.bindFullscreenchange);
    window.addEventListener("beforeunload", this.beforeunload.bind(this));
  }
  public removeEvent() {
    window.removeEventListener("wheel", this.bindWheel);
    window.removeEventListener("contextmenu", this.contextmenu);
    document.removeEventListener("fullscreenchange", this.bindFullscreenchange);
  }

  private wheel(e: WheelEvent) {
    wheel(e, this.draw);
  }

  private beforeunload() {
    this.draw.broadcast({ type: `user_leave` });
  }
  private contextmenu(e: Event) {
    e.stopPropagation();
    e.preventDefault();
  }
  private fullscreenchange() {
    this.draw.getPreviewManager().fullscreenchange();
  }
}
